import * as zrender from "zrender";

class Anchor {
  constructor(node) {
    this.bars = [];
    this.node = node;
    this.create();
  }

  create() {
    const points = this.node.getAnchors();

    points.forEach((point) => {
      const circle = new zrender.Circle({
        style: {
          fill: "#fff",
          stroke: "rgb(0,181,237)",
          lineWidth: 1,
        },
        shape: {
          cx: point.x,
          cy: point.y,
          r: 3,
        },
        cursor: "crosshair",
        z: 30001,
      });

      circle.point = point;
      circle.mark = "anchor";
      circle.node = this.node;
      point.anchor = circle;

      circle.on("mouseover", () => {
        circle.oldfill = circle.style.fill;
        circle.setStyle("fill", "rgb(0,181,237)");
        this.node.time && clearTimeout(this.node.time);
        this.show();
      });

      circle.on("mouseout", () => {
        circle.setStyle("fill", circle.oldfill);
        this.hide();
      });

      circle.on("mousedown", () => {
        circle.setStyle("fill", "rgb(0,181,237)");
      });

      this.bars.push(circle);
    });
  }

  getBarByIndex(index) {
    return this.bars.filter((bar) => {
      return bar.point.index == index;
    })[0]; //this.bars.find((item) => item.point.index === index);
  }

  show() {
    this.bars.forEach((item) => {
      item.show();
    });
  }

  hide() {
    this.bars.forEach((item) => {
      item.hide();
    });
  }

  refresh() {
    this.bars.forEach((item) => {
      const point = this.node.getAnchorsByIndex(item.point.index);
      item.attr({ shape: { cx: point.x, cy: point.y } });
      item.point = point;
    });
  }
}

export default Anchor;
